from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render
from django.core.paginator import Paginator
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from content.models import Goods
from manager.forms.goodsform import GoodsSearchForm, GoodsForm
from common import res_json_data
import json
from common.add_data import test

@csrf_exempt
def goods_manage(request):
    search = GoodsSearchForm()
    return render(request, 'manager/goods_manage/index.html', {'search': search})


@csrf_exempt
def goods_data(request):
    if request.method == 'POST':
        limit = request.POST.get('limit')
        page = request.POST.get('page')
        searchParams = request.POST.get('searchParams')
        if searchParams != None:
            searchParams = json.loads(searchParams)
            negotiation = Goods.objects.filter(name__contains=searchParams['name'],
                                               category__contains=searchParams['category']).order_by('-id')
            page_list = Paginator(negotiation, limit).page(page)
        else:
            negotiation = Goods.objects.all().order_by('-id')
            page_list = Paginator(negotiation, limit).page(page)
        data = []
        index = (int(page) - 1) * int(limit)
        for i in page_list:
            item_dic = {}
            index += 1
            item_dic['index'] = index
            field_names = [f.name for f in i._meta.get_fields()]
            # print('字段名', field_names)
            for key in field_names:
                if key in ['id', 'name', 'category', 'price', 'rating', 'description']:
                    item_dic[key] = getattr(i, key)
                if key in 'images':
                    item_dic[key] = getattr(i, key).url
            data.append(item_dic)
        # print('===============data==', data)
        return res_json_data.table_api(data=data, count=len(negotiation))


@csrf_exempt
def goods_add(request):
    if request.method == 'GET':
        form = GoodsForm()
        return render(request, 'manager/goods_manage/edit.html', {'form': form})
    form = GoodsForm(data=request.POST)
    if form.is_valid():
        form.save()
        messages.success(request, '添加成功')
        return render(request, 'manager/goods_manage/edit.html', {'form': form})
    return render(request, 'manager/goods_manage/edit.html', {'form': form})


@csrf_exempt
def goods_edit(request):
    id = request.GET.get('id')
    user_instance = Goods.objects.get(id=id)
    if request.method == 'GET':
        form = GoodsForm(instance=user_instance)
        return render(request, 'manager/goods_manage/edit.html', {'form': form})
    form = GoodsForm(data=request.POST, instance=user_instance)
    # print('====edit====', request.POST)
    file = request.FILES.get('file')  # 上传的文件
    images = request.FILES.get('images')  # 上传的图片
    # print('====file====', file)
    # print('====images====', images)
    if form.is_valid():
        form.save()
        messages.success(request, '编辑成功')
        return render(request, 'manager/goods_manage/edit.html', {'form': form})

    return render(request, 'manager/goods_manage/edit.html', {'form': form})


@csrf_exempt
def goods_delete(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        Goods.objects.get(id=id).delete()
        return HttpResponse('ok')


@csrf_protect
def goods_collect(request):
    if request.method == 'POST':
        data = request.POST.get('keyword')
        print(f'收到爬取请求，关键词：{data}')

        try:
            test(path=data)  # 调用爬虫函数并传递用户输入
            print('爬取任务已启动')
            return HttpResponse("爬取开始", status=200)
        except Exception as e:
            print('爬取出错：', e)
            return HttpResponse("服务器错误", status=500)